package com.htl.线程.死锁;

public class DeadLockRunnable implements Runnable {
    public int num;
    private static Data data1 = new Data();
    private static Data data2 = new Data();

    @Override
    public void run() {
        if (num == 1) {
            System.out.println(Thread.currentThread().getName() + "获取到了data1，等待获取data2");
            //获取data1
            synchronized (data1){
                try {
                    //这里使用休眠的作用，就是为了出现间歇，以便出现死锁
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //获取data2
                synchronized (data2){
                    System.out.println(Thread.currentThread().getName() + "用餐完毕");
                }
            }
        }
        if (num == 2) {
            System.out.println(Thread.currentThread().getName() + "获取到了data2，等待获取data1");
            //获取data2
            synchronized (data2){
                try {
                    //这里使用休眠的作用，就是为了出现间歇，以便出现死锁
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                //获取data1
                synchronized (data1){
                    System.out.println(Thread.currentThread().getName() + "用餐完毕");
                }
            }
        }
    }
}

